import os

# 广度优先搜索：使用 os.walk
def bfs_count_files_and_folders(path):
    total_files = 0
    total_folders = 0
    root_level = path.count(os.sep)
    for root, dirs, files in os.walk(path):
        current_level = root.count(os.sep) - root_level
        if current_level == 2:
            break
        print("===========")
        print(f"BFS - 当前层级: {current_level}, 当前目录: {root}")
        print(dirs)
        print(files)
        total_folders += len(dirs)
        total_files += len(files)
        # break
    return total_files, total_folders

# 深度优先搜索：递归实现
def dfs_count_files_and_folders(path, level=0):
    total_files = 0
    total_folders = 0
    print(f"DFS - 当前层级: {level}, 当前目录: {path}")
    try:
        for entry in os.scandir(path):
            if entry.is_dir():
                sub_files, sub_folders = dfs_count_files_and_folders(entry.path, level + 1)
                total_files += sub_files
                total_folders += sub_folders + 1
            elif entry.is_file():
                total_files += 1
    except PermissionError:
        pass
    return total_files, total_folders

path = r"D:\迁移文件\第4章 HTML+CSS系列教程①之拨云见日_3"

# 广度优先搜索
print("=== 广度优先搜索结果 ===")
files_bfs, folders_bfs = bfs_count_files_and_folders(path)
print(f"文件总数(包括所有子文件夹中的文件): {files_bfs}")
print(f"文件夹总数(不包括根文件夹): {folders_bfs}")

# # 深度优先搜索
# print("\n=== 深度优先搜索结果 ===")
# files_dfs, folders_dfs = dfs_count_files_and_folders(path)
# print(f"文件总数(包括所有子文件夹中的文件): {files_dfs}")
# print(f"文件夹总数(不包括根文件夹): {folders_dfs}")

# print(f"项目总数: {files_bfs + folders_bfs}")